package com.vito.careworker;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;

import com.vito.base.action.Action;
import com.vito.base.action.ActionParser;
import com.vito.base.action.LoginSuccessfullyAction;
import com.vito.base.helper.StartUpHelper;
import com.vito.base.ui.ActionBarCtrller;
import com.vito.base.ui.VitoBaseActivity;
import com.vito.base.ui.fragments.BaseFragment;
import com.vito.base.ui.fragments.FragmentFactory;
import com.vito.base.update.UpdateService;
import com.vito.base.utils.ToastShow;
import com.vito.base.utils.network.httplibslc.JsonLoaderCallBack;
import com.vito.careworker.account.LoginInfo;
import com.vito.careworker.account.LoginResult;
import com.vito.careworker.fragments.GuideFragment;
import com.vito.careworker.fragments.LoginFragment;
import com.vito.careworker.fragments.MainActivityFragment;
import com.vito.careworker.helpers.HomeMoreFunHelper;
import com.vito.careworker.helpers.MoreHelper;
import com.vito.careworker.utils.Comments;

import de.greenrobot.event.EventBus;

public class MainActivity extends VitoBaseActivity implements JsonLoaderCallBack,BaseFragment.BackHandledInterface{

    private static final String TAG = MainActivity.class.getName();
    /**
     * 当前ECLauncherUI 实例
     */
    public static MainActivity mLauncherUI;
    public UpdateService mService = null;
    boolean mFragmentInited = false;
    boolean mIsLogin = false;
    private Handler mWorkingHandler = null;
    private boolean mIsActivityDestroyed = false;
    private BaseFragment mCurrentFragment = null;
    private int mBackKeyPressedTimes = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.start_page_3));
        setStatusBarTintResource(android.R.color.transparent);
        LoginInfo.getInstance().init(this);
        HomeMoreFunHelper.getInstance().init(this);
        MoreHelper.getInstance().init(this);
        if (mLauncherUI != null) {
            mLauncherUI.finish();
        }
        mLauncherUI = this;
        mWorkingHandler = new Handler();
        mWorkingHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initFragment();
            }
        }, Comments.START_WAIT_TIME);
    }

    @Override
    public void initActionBar() {
        super.initActionBar();
        ActionBarCtrller.getInstance().setActionBarBg(getResources().getColor(R.color.myinfo_actionbar_bg));
        ActionBarCtrller.getInstance().setLeftImgRes(R.drawable.pic_52);
    }

    private void initFragment() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                findViewById(com.vito.base.R.id.rootfragcontent).setBackgroundResource(android.R.color.white);
                getWindow().setBackgroundDrawableResource(android.R.color.white);
                setStatusBarTintResource(R.color.colorPrimary2);
            }
        });

        Fragment newFragment = null;
        boolean firstBoot = StartUpHelper.getInstance(this).isFirstOpen();
        if (firstBoot)
            newFragment = FragmentFactory.getInstance().createFragment(GuideFragment.class);
        else if (LoginResult.getInstance().isImIsLoginOK())
            newFragment = FragmentFactory.getInstance().createFragment(MainActivityFragment.class);
        else
            newFragment = FragmentFactory.getInstance().createFragment(LoginFragment.class);
//            newFragment = FragmentFactory.getInstance().createFragment(MainActivityFragment.class);

        final FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        if (R.id.rootfragcontent != 0) {
            transaction.replace(R.id.rootfragcontent, newFragment);
            transaction.commitAllowingStateLoss();
        }

        mFragmentInited = true;
//        checkPermission(this);
    }

    public boolean checkPermission(Activity in_act) {
        if (ContextCompat.checkSelfPermission(in_act, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(in_act, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(in_act, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(in_act, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(in_act, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(in_act, Manifest.permission.WRITE_SETTINGS) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(in_act, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(in_act, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                ) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(in_act, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_SETTINGS,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO

            }, 0);
        }
        return false;
    }

    @Override
    public void onJsonDataGetSuccess(Object re_data, int reqcode) {

    }

    @Override
    public void onJsonDataGetFailed(int re_code, String re_info, int reqcode) {

    }

    @Override
    public void setSelectedFragment(BaseFragment selectedFragment) {
        mCurrentFragment = selectedFragment;
        if (!(mCurrentFragment instanceof LoginFragment))
            mIsLogin = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        mIsActivityDestroyed = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    public synchronized void onEventMainThread(Action event) {
        String eventtype = event.getmActionType();
        if (eventtype.equals("DoHisAction")) {
            mWorkingHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ActionParser.getInstance().parseAction(MainActivity.this, LoginSuccessfullyAction.getOnLoginSuccessfully(), true);
                    LoginSuccessfullyAction.setOnLoginSuccessfully(null);
                }
            }, 500);

        }
    }

    public void onBackPressed() {
        if (!mFragmentInited)
            return;
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {

            Fragment topfragment = getSupportFragmentManager().findFragmentById(R.id.rootfragcontent);
            if (mBackKeyPressedTimes == 0) {
                if ((topfragment instanceof MainActivityFragment) || (topfragment instanceof LoginFragment)) {
                    mBackKeyPressedTimes = 1;
                    ToastShow.toastShow(R.string.login_exit, ToastShow.LENGTH_SHORT);
                } else
                    initFragment();

                new Thread() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            mBackKeyPressedTimes = 0;
                        }
                    }
                }.start();
                return;
            } else if (mBackKeyPressedTimes == 1) {
                super.onBackPressed();
                return;
            }
            super.onBackPressed();
        } else {
            if (mCurrentFragment != null && mCurrentFragment.onBackPressed()) {
                return;
            }
            getSupportFragmentManager().popBackStackImmediate();
            return;
        }
    }
}
